#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
账号管理数据访问层
"""

import logging
from typing import List, Optional
from models.base import db
from models.belong import Belong, ClientType
from sqlalchemy.exc import SQLAlchemyError

class AccountDAO:
    """
    账号管理数据访问层
    专门负责belongs表的数据库操作
    """
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
    
    def get_all_accounts(self) -> List[Belong]:
        """
        获取所有账号
        
        Returns:
            List[Belong]: 账号列表
        """
        try:
            res = Belong.query.order_by(Belong.created_at.desc()).all()
            self.logger.info(f"dao 层获取账号列表成功，共 {len(res)} 个账号")
            self.logger.info(f"dao 层账号列表 res: {res}")
            return res
        except SQLAlchemyError as e:
            self.logger.error(f"获取账号列表失败: {e}")
            raise
    
    def get_account_by_id(self, account_id: str) -> Optional[Belong]:
        """
        根据ID获取账号
        
        Args:
            account_id (str): 账号ID
            
        Returns:
            Optional[Belong]: 账号对象或None
        """
        try:
            return Belong.query.filter_by(id=account_id).first()
        except SQLAlchemyError as e:
            self.logger.error(f"根据ID获取账号失败: {e}")
            raise
    
    def get_account_by_name(self, account_name: str) -> Optional[Belong]:
        """
        根据账号名获取账号
        
        Args:
            account_name (str): 账号名
            
        Returns:
            Optional[Belong]: 账号对象或None
        """
        try:
            return Belong.query.filter_by(account=account_name).first()
        except SQLAlchemyError as e:
            self.logger.error(f"根据账号名获取账号失败: {e}")
            raise
    
    def create_account(self, data: dict) -> Belong:
        """
        创建账号
        
        Args:
            data (dict): 账号数据
            
        Returns:
            Belong: 创建的账号对象
        """
        try:
            account = Belong(
                account=data['account'],
                alias=data['alias'],
                account_type=ClientType(data.get('account_type', 'wechat'))
            )
            
            db.session.add(account)
            db.session.commit()
            
            return account
            
        except SQLAlchemyError as e:
            db.session.rollback()
            self.logger.error(f"创建账号失败: {e}")
            raise
    
    def update_account(self, account_id: str, data: dict) -> Belong:
        """
        更新账号
        
        Args:
            account_id (str): 账号ID
            data (dict): 更新数据
            
        Returns:
            Belong: 更新后的账号对象
        """
        try:
            account = Belong.query.filter_by(id=account_id).first()
            if not account:
                raise ValueError(f"账号不存在: {account_id}")
            
            # 更新字段
            if 'account' in data:
                account.account = data['account']
            if 'alias' in data:
                account.alias = data['alias']
            if 'account_type' in data:
                account.account_type = ClientType(data['account_type'])
            
            db.session.commit()
            
            return account
            
        except SQLAlchemyError as e:
            db.session.rollback()
            self.logger.error(f"更新账号失败: {e}")
            raise
    
    def delete_account(self, account_id: str) -> bool:
        """
        删除账号
        
        Args:
            account_id (str): 账号ID
            
        Returns:
            bool: 删除是否成功
        """
        try:
            account = Belong.query.filter_by(id=account_id).first()
            if not account:
                raise ValueError(f"账号不存在: {account_id}")
            
            db.session.delete(account)
            db.session.commit()
            
            return True
            
        except SQLAlchemyError as e:
            db.session.rollback()
            self.logger.error(f"删除账号失败: {e}")
            raise
    
    def get_accounts_by_type(self, account_type: ClientType) -> List[Belong]:
        """
        根据账号类型获取账号列表
        
        Args:
            account_type (ClientType): 账号类型
            
        Returns:
            List[Belong]: 账号列表
        """
        try:
            return Belong.query.filter_by(account_type=account_type).order_by(Belong.created_at.desc()).all()
        except SQLAlchemyError as e:
            self.logger.error(f"根据类型获取账号列表失败: {e}")
            raise
    
    def search_accounts(self, keyword: str) -> List[Belong]:
        """
        搜索账号
        
        Args:
            keyword (str): 搜索关键词
            
        Returns:
            List[Belong]: 匹配的账号列表
        """
        try:
            return Belong.query.filter(
                db.or_(
                    Belong.account.like(f'%{keyword}%'),
                    Belong.alias.like(f'%{keyword}%')
                )
            ).order_by(Belong.created_at.desc()).all()
        except SQLAlchemyError as e:
            self.logger.error(f"搜索账号失败: {e}")
            raise